/**
 * The MIT License (MIT)
 * Copyright (c) 2021 铭软科技(mingsoft.net)
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package net.mingsoft.basic.action;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.*;
import net.mingsoft.base.entity.ResultData;
import net.mingsoft.base.util.JSONObject;
import net.mingsoft.basic.action.q.ManagerListQuery;
import net.mingsoft.basic.action.q.ManagerSearchQuery;
import net.mingsoft.basic.action.r.ManagerResponse;
import net.mingsoft.basic.annotation.LogAnn;
import net.mingsoft.basic.bean.EUListBean;
import net.mingsoft.basic.biz.IManagerBiz;
import net.mingsoft.basic.constant.e.BusinessTypeEnum;
import net.mingsoft.basic.constant.e.SessionConstEnum;
import net.mingsoft.basic.entity.ManagerEntity;
import net.mingsoft.basic.entity.ManagerSessionEntity;
import net.mingsoft.basic.sao.SM4CloudService;
import net.mingsoft.basic.util.ApplicationContextUtil;
import net.mingsoft.basic.util.BasicUtil;
import net.mingsoft.basic.util.SpringUtil;
import net.mingsoft.basic.util.StringUtil;
import net.mingsoft.flk.entity.FlkEncryption;
import net.mingsoft.flk.entity.vo.Role;
import net.mingsoft.flk.enums.FlkType;
import net.mingsoft.flk.service.Impl.FlkEncryptionServiceImpl;
import net.mingsoft.flk.service.Impl.RoleServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 管理员管理控制层
 * @author 铭飞开发团队
 * @version
 * 版本号：1.0<br/>
 * 创建日期：2017-8-24 23:40:55<br/>
 * 历史修订：<br/>
 */
@Api(value = "管理员管理接口", tags = {"管理员-管理接口"})
@Controller
@RequestMapping("/${ms.manager.path}/basic/manager")
public class ManagerAction extends BaseAction{

	/**
	 * 注入管理员业务层
	 */
	@Autowired
	private IManagerBiz managerBiz;

	@Resource
	ConcurrentMapCacheManager cacheManager;

	@Resource
	private RoleServiceImpl roleService;

	@Resource
	private FlkEncryptionServiceImpl flkEncryptionService;

	/**
	 * 返回主界面index
	 */
	@GetMapping("/index")
	public String index(HttpServletResponse response,HttpServletRequest request){
		return "/basic/manager/index";
	}

	@ApiOperation(value = "查询管理员列表")
	@PostMapping(value = "/search", consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiResponses(value = {
			@ApiResponse(code = 200, message = "success", response = ManagerEntity.class)
	})
	public ResultData search(@RequestBody ManagerSearchQuery query) {
		Page<ManagerEntity> page = managerBiz.search(query);
		return ResultData.build().success(page);
	}

	@ApiOperation(value = "校验")
	@PostMapping(value = "/verify", consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResultData verify(@RequestBody ManagerResponse managerResponse) {
		// 转换抽JSON
		String json = JSONObject.toJSONStringWithDateFormat(managerResponse, "yyyy-MM-dd HH:mm:ss");
		return flkEncryptionService.verification(FlkType.USER.getCode(), managerResponse.getId(), json);
	}


	@ApiOperation(value = "查询管理员列表")
	@ApiResponses(value = {
			@ApiResponse(code = 200, message = "success", response = ManagerResponse.class)
	})
	@PostMapping(value = "/list", consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResultData list(@RequestBody ManagerListQuery query) {
		Page<ManagerResponse> page = managerBiz.managerList(query);
		for (ManagerResponse record : page.getRecords()) {
			setStatus(record);
		}
		return ResultData.build().success(page);
	}

	public void setStatus(ManagerResponse managerEntity) {
		Cache cache = cacheManager.getCache("login-retry-times");
		if (cache != null) {
			Cache.ValueWrapper valueWrapper = cache.get(managerEntity.getAccount() + "-expired");
			if (valueWrapper != null) {
				DateTime expired = (DateTime) valueWrapper.get();
				if (DateTime.now().isBefore(expired)) {
					managerEntity.setStatus("DISABLED");
				}
			}
		}
	}

	@ApiOperation(value = "查询管理员列表,去掉当前管理员id，确保不能删除和修改自己")
	@GetMapping("/query")
	@ResponseBody
	public ResultData query(HttpServletResponse response, HttpServletRequest request, @ApiIgnore ModelMap model) {
		ManagerSessionEntity managerSession = getManagerBySession();
		BasicUtil.startPage();
		List<ManagerEntity> managerList = managerBiz.queryAllChildManager(Integer.parseInt(managerSession.getId()));
		for(ManagerEntity _manager : managerList){
			if(_manager.getId().equals(managerSession.getId())){
				_manager.setId("0");
			}
		}
		return ResultData.build().success(new EUListBean(managerList,(int)BasicUtil.endPage(managerList).getTotal()));
	}

	@ApiOperation(value="获取管理员接口")
	@GetMapping("/get")
	@ResponseBody
	public ResultData get(@ModelAttribute @ApiIgnore ManagerEntity manager,HttpServletResponse response, HttpServletRequest request,@ApiIgnore ModelMap model){
		ManagerEntity managerEntity = new ManagerEntity();
		//判断是否传managerId
		if(StringUtils.isNotEmpty(manager.getId())){
			managerEntity = (ManagerEntity)managerBiz.getById(Integer.parseInt(manager.getId()));
		}else{
			ManagerEntity managerSession = (ManagerEntity) BasicUtil.getSession(SessionConstEnum.MANAGER_SESSION);
			managerEntity = (ManagerEntity)managerBiz.getById(Integer.parseInt(managerSession.getId()));
		}
		if(managerEntity==null) {
			LOG.debug("login manager is null");
			SecurityUtils.getSubject().logout();
		}
		setStatus(managerEntity);
		managerEntity.setManagerPassword("");
		return ResultData.build().success(managerEntity);
	}

	public void setStatus(ManagerEntity managerEntity) {
		Cache cache = cacheManager.getCache("login-retry-times");
		if (cache != null) {
			Cache.ValueWrapper valueWrapper = cache.get(managerEntity.getManagerName() + "-expired");
			if (valueWrapper != null) {
				DateTime expired = (DateTime) valueWrapper.get();
				if (DateTime.now().isBefore(expired)) {
					managerEntity.setStatus("DISABLED");
				}
			}
		}
	}

	@ApiOperation(value = "保存管理员实体")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "managerName", value = "帐号", required = true,paramType="query"),
		@ApiImplicitParam(name = "managerNickName", value = "昵称", required = true,paramType="query"),
		@ApiImplicitParam(name = "managerPassword", value = "密码", required = true,paramType="query"),
		@ApiImplicitParam(name = "roleId", value = "角色ID", required = false,paramType="query"),
		@ApiImplicitParam(name = "peopleId", value = "用户ID", required = false,paramType="query"),
		@ApiImplicitParam(name = "status", value = "状态：ENABLED、DISABLED", required = false,paramType="query"),
	})
	@LogAnn(title = "保存管理员实体",businessType= BusinessTypeEnum.INSERT)
	@PostMapping("/save")
	@ResponseBody
	@RequiresPermissions("manager:save")
	@Transactional(rollbackFor = Exception.class)
	public ResultData save(@ModelAttribute @ApiIgnore ManagerEntity manager, HttpServletResponse response, HttpServletRequest request) {
		//用户名是否存在
		if (managerBiz.getManagerByManagerName(manager.getManagerName()) != null) {
			return ResultData.build().error(getResString("err.exist", this.getResString("manager.name")));
		}
		//验证管理员用户名的值是否合法
		if (StringUtil.isBlank(manager.getManagerName())) {
			return ResultData.build().error(getResString("err.empty", this.getResString("manager.name")));
		}
		if (!StringUtil.checkLength(manager.getManagerName() + "", 1, 15)) {
			return ResultData.build().error(getResString("err.length", this.getResString("manager.name"), "1", "15"));
		}
		//验证管理员昵称的值是否合法
		if (StringUtil.isBlank(manager.getManagerNickName())) {
			return ResultData.build().error(getResString("err.empty", this.getResString("manager.nickname")));
		}
		if (!StringUtil.checkLength(manager.getManagerNickName() + "", 1, 15)) {
			return ResultData.build().error(getResString("err.length", this.getResString("manager.nickname"), "1", "15"));
		}
		//验证管理员密码的值是否合法
		if (StringUtil.isBlank(manager.getManagerPassword())) {
			return ResultData.build().error(getResString("err.empty", this.getResString("manager.password")));
		}
		if (!StringUtil.checkLength(manager.getManagerPassword() + "", 1, 45)) {
			return ResultData.build().error(getResString("err.length", this.getResString("manager.password"), "1", "45"));
		}
		if (!passwordPatternRequired(manager.getManagerPassword())) {
			return ResultData.build().error("密码强度太低！需要至少8位，且包含字符、数字和大写字母、小写字母任意三种组合");
		}
		manager.setManagerPassword(SecureUtil.md5(manager.getManagerPassword()));

		// flk sm4 安全加密
		String encryptedPassword = SpringUtil.getApplicationContext().getBean(SM4CloudService.class)
				.encrypt(manager.getManagerPassword());
		manager.setManagerPassword(encryptedPassword);

		// manager.setManagerPassword(SecureUtil.md5(manager.getManagerPassword()));
		manager.setUpdatePwdDate(new Date());
		managerBiz.saveEntity(manager);

		ManagerResponse managerResponse = get(manager);
		String json = JSONObject.toJSONStringWithDateFormat(managerResponse, "yyyy-MM-dd HH:mm:ss");
		FlkEncryption flkEncryption = flkEncryptionService.saveFlkEncryption(FlkType.USER.getCode(), manager.getId(), json);
		return ResultData.build().success(manager);
	}


	@ApiOperation(value = "批量删除管理员")
	@LogAnn(title = "批量删除管理员",businessType= BusinessTypeEnum.DELETE)
	@PostMapping("/delete")
	@ResponseBody
	@RequiresPermissions("manager:del")
	public ResultData delete(@RequestBody List<ManagerEntity> managers,HttpServletResponse response, HttpServletRequest request) {
		int[] ids = new int[managers.size()];
		for(int i = 0;i<managers.size();i++){
			ids[i] = Integer.parseInt(managers.get(i).getId());
		}
		managerBiz.delete(ids);
		managerBiz.updateCache();
		return ResultData.build().success();
	}

	@ApiOperation(value = "更新管理员信息管理员")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "managerName", value = "帐号", required = true,paramType="query"),
		@ApiImplicitParam(name = "managerNickName", value = "昵称", required = true,paramType="query"),
		@ApiImplicitParam(name = "managerPassword", value = "密码", required = true,paramType="query"),
		@ApiImplicitParam(name = "roleId", value = "角色ID", required = false,paramType="query"),
		@ApiImplicitParam(name = "peopleId", value = "用户ID", required = false,paramType="query"),
		@ApiImplicitParam(name = "status", value = "状态：ENABLED、DISABLED", required = false,paramType="query"),
	})
	@LogAnn(title = "更新管理员信息管理员",businessType= BusinessTypeEnum.UPDATE)
	@PostMapping("/update")
	@ResponseBody
	@RequiresPermissions("manager:update")
	public ResultData update(@ModelAttribute @ApiIgnore ManagerEntity manager) {
		// managerBiz.updateCache();
		ManagerEntity _manager = managerBiz.getManagerByManagerName(manager.getManagerName());
		//用户名是否存在
		if (_manager != null) {
			if (!_manager.getId().equals(manager.getId())) {
				return ResultData.build().error(getResString("err.exist", this.getResString("manager.name")));
			}
			if (StringUtils.isBlank(manager.getManagerPassword())) {
				manager.setManagerPassword(_manager.getManagerPassword());
			} else {
				if (!passwordPatternRequired(manager.getManagerPassword())) {
					return ResultData.build().error("密码强度太低！需要至少8位，且包含字符、数字和大写字母、小写字母任意三种组合");
				}
				manager.setManagerPassword(SecureUtil.md5(manager.getManagerPassword()));

				// flk sm4 安全加密
				String encryptedPassword = SpringUtil.getApplicationContext().getBean(SM4CloudService.class)
						.encrypt(manager.getManagerPassword());
				manager.setManagerPassword(encryptedPassword);

				manager.setUpdatePwdDate(new Date());
			}
		}
		//验证管理员用户名的值是否合法
		if (StringUtil.isBlank(manager.getManagerName())) {
			return ResultData.build().error(getResString("err.empty", this.getResString("manager.name")));
		}
		if (!StringUtil.checkLength(manager.getManagerName() + "", 1, 15)) {
			return ResultData.build().error(getResString("err.length", this.getResString("manager.name"), "1", "15"));
		}
		//验证管理员昵称的值是否合法
		if (StringUtil.isBlank(manager.getManagerNickName())) {
			return ResultData.build().error(getResString("err.empty", this.getResString("manager.nickname")));
		}
		if (!StringUtil.checkLength(manager.getManagerNickName() + "", 1, 15)) {
			return ResultData.build().error(getResString("err.length", this.getResString("manager.nickname"), "1", "15"));
		}
		//验证管理员密码的值是否合法
		/*if(!StringUtil.isBlank(manager.getManagerPassword())){
			if(!StringUtil.checkLength(manager.getManagerPassword()+"", 1, 45)){
				return ResultData.build().error(getResString("err.length", this.getResString("manager.password"), "1", "45"));
			}
			manager.setManagerPassword(SecureUtil.md5(manager.getManagerPassword()));
		} else {
			manager.setManagerPassword(null);
		}*/
		if (managerBiz.updateByMangerId(manager)) {
			evictLockStatus(manager);
		}
		;
		ManagerResponse managerResponse = get(manager);
		flkEncryptionService.updateFlkEncryption(FlkType.USER.getCode(), manager.getId(), JSONObject.toJSONStringWithDateFormat(managerResponse, "yyyy-MM-dd HH:mm:ss"));

		return ResultData.build().success(manager);
	}

	private ManagerResponse get(ManagerEntity manager) {
		ManagerResponse managerResponse = new ManagerResponse();
		ManagerEntity it = managerBiz.getById(Integer.parseInt(manager.getId()));
		Role role = roleService.getById(it.getRoleId());
		managerResponse.setId(it.getId())
				.setAccount(it.getManagerName())
				.setNickName(it.getManagerNickName())
				.setRoleName(role.getRoleName())
				.setCreatedDate(it.getCreateDate())
				.setStatus(it.getStatus()).setDepartName(it.getDepartName()).setPost(it.getPost());
		return managerResponse;
	}


	//	private static final String PASSWORD_PATTERN = "^(?![a-zA-Z]+)(?![0-9]+)(?![!@#$%^&*()_+-=`~<>?,./:\";'])[a-zA-Z0-9!@#$%^&*()_+-=`~<>?,./:\";']{8,}$";
//	private static final String PASSWORD_PATTERN = "^(?=.*\\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*])[\\da-zA-Z~!@#$%^&*]{8,30}$";
	private static final String P_DIGIT = ".*[0-9]+.*";
	private static final String P_ALPHA = ".*[a-z]+.*";
	private static final String P_ALPHA2 = ".*[A-Z]+.*";

	private static final String P_SYMBOL = ".*[\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)\\_\\+\\-\\=\\`\\~\\<\\>\\?\\,\\.\\/\\:\\\"\\;\\']+.*";

	/**
	 * 密码校验
	 * @return 至少包含3种不同的字符组合（大小写字母算2种）
	 */
	public boolean passwordPatternRequired(String a) {
		int n = 0;
		if (StringUtils.isNotBlank(a)) {
			if (a.matches(P_DIGIT)) {
				n += 1;
			}
			if (a.matches(P_ALPHA)) {
				n += 1;
			}
			if (a.matches(P_ALPHA2)) {
				n += 1;
			}
			if (a.matches(P_SYMBOL)) {
				n += 1;
			}
		}
		return n >= 3 && StringUtils.isNotBlank(a) && StringUtils.length(a) >= 8;
	}

	/**
	 * 手动清除锁定状态
	 * @param manager 用户
	 */
	public void evictLockStatus(ManagerEntity manager) {
		if (manager.getStatus().equals("ENABLED")) {
			Cache cache = cacheManager.getCache("login-retry-times");
			if (cache != null) {
				Cache.ValueWrapper valueWrapper = cache.get(manager.getManagerName() + "-expired");
				if (valueWrapper != null) {
					cache.evict(manager.getManagerName() + "-expired");
					cache.evict(manager.getManagerName() + "-times");
				}
			}
		}
	}

}
